<?php

class ApplicationController extends Yaf\Controller_Abstract {

    /**
     * 配置文件
     *
     * @var Yaf\Config\Ini
     */
    protected $config;

    /**
     * @var 当前登录用户信息
     */
    protected $user;

    public function init() {
        Yaf\Dispatcher::getInstance()->disableView();
        $this->user = $this->getRequest()->user ?? null;
        $this->config = Yaf\Registry::get('config');
    }


    public function __set($name, $value) {
        $this->$name = $value;
    }

    public function getConfig() {
        return $this->config;
    }

    /**
     * @return int 当前登录用户id
     */
    public function getUserId()
    {
        return (int)$this->user->id;
    }

    /**
     * @return 当前登录用户信息
     */
    public function getUser()
    {
        return $this->user;
    }

    /** 获取get或路由参数，null返回所有参数
     * @param null $name
     * @return mixed|null
     */
    public function get($name = null)
    {
        //静态路由没有$_GET
        if (!$_GET) {
            $_GET = $this->getRequest()->getParams();
        }

        if (!$name) {
            $data = $_GET;
        } elseif (isset($_GET[$name])) {
            $data = $_GET[$name];
        } else {
            return false;
        }

        return $this->xssClean($data);
    }

    /** 获取post请求参数，null返回所有参数
     * @param null $name
     * @return mixed|null
     */
    public function post($name = null)
    {

        if (!$name) {
            $data = $_POST;
        } elseif (isset($_POST[$name])) {
            $data = $_POST[$name];
        } else {
            return false;
        }

        return $this->xssClean($data);
    }

    /** 获取cookie参数，null返回所有参数
     * @param null $name
     * @return bool|mixed
     */
    public function cookie($name = null)
    {
        if (!$name) {
            $data = $_COOKIE;
        } elseif (isset($_COOKIE[$name])) {
            $data = $_COOKIE[$name];
        } else {
            return false;
        }

        return $this->xssClean($data);
    }

    /** xss攻击过滤
     * @param $data
     * @return mixed
     */
    public function xssClean($data)
    {
        /*if (is_array($data)) {
            return filter_var_array($data, FILTER_SANITIZE_STRING);
        } else {
            return filter_var($data, FILTER_SANITIZE_STRING);
        }*/
        return $data;
    }

    /** 输出json格式http响应
     * @param null $data  响应的数据
     * @param null $msg   响应的消息内容
     * @param int $code   错误码
     */
    public function json($data = null, $msg = null, $code = 200)
    {
        $res = ['code' => $code];
        if ($msg !== null) {
            $res['message'] = $msg;
        }
        if ($data !== null) {
            $res['data'] = $data;
        }

        header('Content-Type: application/json;charset=utf-8');
        echo json_encode($res, JSON_UNESCAPED_UNICODE);
    }

}
